package com.eazy.lkv2.core.util;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

/**
 * Created by hpb on 2018/5/4.
 */
public class QiniuUpload {
    public static final  String IMG_HOST="http://7xqy18.com1.z0.glb.clouddn.com/";
    private static final String ACCESS_KEY = "6gQuIgmq65Sef9Rmv9F4HQqmCnzyaNshD696NdD1";
    private static final String SECRET_KEY = "XH0HXpJDiahTBfgRubFvMr2dkbHQpEjS4rc5Z1vH";

    private static final Logger logger = LoggerFactory.getLogger(QiniuUpload.class);

    public static void upload(String name, InputStream inputStream) {
        Configuration cfg = new Configuration(Zone.zone0());

        UploadManager uploadManager = new UploadManager(cfg);
        String bucket = "staticfile";

        try {
            logger.info("upload img:"+name);
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream, name, upToken, null, null);
                String result=response.bodyString();
//                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                logger.info("upload succeed:"+result);
//                System.out.println(putRet.key);
//                System.out.println(putRet.hash);
                return;
            } catch (QiniuException ex) {
                Response r = ex.response;
                logger.error(r.toString());
                try {
                    logger.error(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        logger.info("upload img to qiniu failed");
    }
//    public static void main(String[]args) throws FileNotFoundException {
//        File file=new File("/Users/hpb/Desktop/appid.rtf");
//        upload("000.jpg",new FileInputStream(file));
//    }
}
